import { useState, useEffect } from 'react';
import { SearchConfigComponentProps } from './types';

export const SearchConfigComponent = ({ config, onChange }: SearchConfigComponentProps) => {
  const [localConfig, setLocalConfig] = useState(config);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});

  // 验证单个字段
  const validateField = (name: string, value: any): string => {
    switch (name) {
      case 'engine':
        if (!value) return '请选择一个搜索引擎';
        return '';
      
      case 'max_retries':
        if (isNaN(value) || value < 0) return '最大重试次数必须为非负整数';
        if (value > 10) return '最大重试次数不能超过10次';
        return '';
      
      case 'retry_delay':
        if (isNaN(value) || value < 1) return '重试延迟必须大于等于1秒';
        if (value > 300) return '重试延迟不能超过300秒';
        return '';
        
      default:
        return '';
    }
  };

  // 验证整个表单
  const validateForm = (data: typeof localConfig): Record<string, string> => {
    const newErrors: Record<string, string> = {};
    
    // 验证每个字段
    Object.entries(data).forEach(([key, value]) => {
      const error = validateField(key, value);
      if (error) {
        newErrors[key] = error;
      }
    });
    
    return newErrors;
  };

  // 处理触摸状态（用户是否与字段交互过）
  const handleBlur = (e: React.FocusEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name } = e.target;
    setTouched(prev => ({ ...prev, [name]: true }));
    
    // 验证单个字段
    const error = validateField(name, localConfig[name as keyof typeof localConfig]);
    setErrors(prev => ({ ...prev, [name]: error }));
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    let parsedValue: string | number = value;
    
    if (name === 'max_retries' || name === 'retry_delay') {
      parsedValue = parseInt(value, 10);
    }

    const updatedConfig = {
      ...localConfig,
      [name]: parsedValue
    };
    
    setLocalConfig(updatedConfig);
    
    // 如果字段已经被触摸过，验证它
    if (touched[name]) {
      const error = validateField(name, parsedValue);
      setErrors(prev => ({ ...prev, [name]: error }));
    }
    
    onChange(updatedConfig);
  };

  // 初始验证
  useEffect(() => {
    const formErrors = validateForm(localConfig);
    setErrors(formErrors);
  }, []);

  return (
    <div className="space-y-6">
      <h2 className="text-lg font-medium">搜索配置</h2>
      <p className="text-sm text-gray-500">配置自动化任务中使用的搜索引擎和重试策略。</p>
      
      <div className="space-y-4">
        <h3 className="text-md font-medium">搜索引擎</h3>
        
        <div>
          <label htmlFor="engine" className="block text-sm font-medium text-gray-700 mb-1">
            搜索引擎
          </label>
          <select
            id="engine"
            name="engine"
            value={localConfig.engine}
            onChange={handleInputChange}
            onBlur={handleBlur}
            className={`w-full p-2 border ${errors.engine ? 'border-red-500' : 'border-gray-300'} rounded-md`}
          >
            <option value="">-- 请选择搜索引擎 --</option>
            <option value="Google">Google</option>
            <option value="Baidu">Baidu</option>
            <option value="DuckDuckGo">DuckDuckGo</option>
          </select>
          {errors.engine && touched.engine && (
            <p className="mt-1 text-xs text-red-500">{errors.engine}</p>
          )}
          <p className="mt-1 text-xs text-gray-500">选择自动化任务使用的搜索引擎。</p>
        </div>
        
        <div className="space-y-4 mt-6">
          <h3 className="text-md font-medium">重试策略</h3>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="max_retries" className="block text-sm font-medium text-gray-700 mb-1">
                最大重试次数
              </label>
              <input
                type="number"
                id="max_retries"
                name="max_retries"
                min="0"
                max="10"
                step="1"
                value={localConfig.max_retries}
                onChange={handleInputChange}
                onBlur={handleBlur}
                className={`w-full p-2 border ${errors.max_retries ? 'border-red-500' : 'border-gray-300'} rounded-md`}
              />
              {errors.max_retries && touched.max_retries && (
                <p className="mt-1 text-xs text-red-500">{errors.max_retries}</p>
              )}
              <p className="mt-1 text-xs text-gray-500">搜索失败时的最大重试次数 (0-10)。</p>
            </div>
            
            <div>
              <label htmlFor="retry_delay" className="block text-sm font-medium text-gray-700 mb-1">
                重试延迟（秒）
              </label>
              <input
                type="number"
                id="retry_delay"
                name="retry_delay"
                min="1"
                max="300"
                step="1"
                value={localConfig.retry_delay}
                onChange={handleInputChange}
                onBlur={handleBlur}
                className={`w-full p-2 border ${errors.retry_delay ? 'border-red-500' : 'border-gray-300'} rounded-md`}
              />
              {errors.retry_delay && touched.retry_delay && (
                <p className="mt-1 text-xs text-red-500">{errors.retry_delay}</p>
              )}
              <p className="mt-1 text-xs text-gray-500">重试之间的等待时间（以秒为单位）。</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SearchConfigComponent; 